<script setup>

import {Plus} from "@element-plus/icons-vue";
import {ElAvatar, ElMessage, ElMessageBox} from "element-plus";
import {ref} from "vue";
import {getTeacherInfo,} from '@/api/student.js';
import {uploadAddProjectFile, deleteProjectFile, exportProject, addProject} from '@/api/project.js'
import {useUserStore} from "@/stores/user.js";

const  teacher_display = ref(false)
const  teacher_data = ref([]);
const  teacher_total = ref(0)
const  selete_teacher = ref(null)
const userStore = useUserStore()


const userId = userStore.userDetails.userId;
const userName = userStore.userDetails.userName;

const AddProject =ref({
  userId:  userId,
  userName:  userName,
  teacherId: null,
  teacherName: null,
  projectName: null,
  description: null,
  startTime: null,
  endTime: null,
  image: null,
  lab: null,
  type: 0,
})
const filters_teacher = ref({
  userName:null,
  professional:null,

  pageNum:1,
  pageSize:5
})

// 添加项目
const handleAddProject = async (AddProject) => {
  // 使用 ElMessageBox 确认
  ElMessageBox.confirm('您确定要添加这个项目吗?', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(async () => {
        // 用户点击确定后执行添加项目的逻辑
        const response = await addProject(AddProject);
        if (response.data.code === 200) {
          AddProject.value = response.data.data;
          ElMessage.success('添加成功');

        } else {
          ElMessage.error(response.data.msg || '添加失败');
        }
      })
      .catch(() => {
        // 用户点击取消的逻辑
        ElMessage.info('已取消添加项目');
      });
};

// 获取教师信息
const fetchTeachers = async () => {
  teacher_display.value = true;
  const response = await getTeacherInfo(filters_teacher.value);
  if (response.data.code === 200) {
    teacher_data.value = response.data.data.rows;
    console.log(teacher_data.value)
    teacher_total.value = response.data.data.total;
  } else {
    ElMessage.error(response.data.msg);
  }
}

// 重置筛选条件
const resetFilters_teacher = () => {
  filters_teacher.value = {
    userName:null,
    professional:null,
    pageNum:1,
    pageSize:5
  }
  fetchTeachers();
}
const handleTeacherPageChange = (page) => {
  filters_teacher.value.pageNum = page;
  fetchTeachers();
};
// 上传图片
const uploadImage = async ({ file }) => {
  const formData = new FormData();
  formData.append('file', file);
  try {
    const response = await uploadAddProjectFile(formData);
    if (response.data.code === 200) {
      AddProject.value.image = response.data.data; // 假设后端返回图片 URL
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error(response.data.msg || '图片上传失败');
    }
  } catch (error) {
    ElMessage.error('接口请求失败');
  }
};

// 删除图片
const handleDeleteImage = async () => {
  try {
    const response = await deleteProjectFile(AddProject.value.image);
    if (response.data.code === 200) {
      AddProject.value.image = null;
      ElMessage.success('图片删除成功');
    } else {
      ElMessage.error(response.data.msg || '图片删除失败');
    }
  } catch (error) {
    ElMessage.error('接口请求失败');
  }
};
// 选择导师
const handleSelectTeacher = (teacher) => {
  if(AddProject.value.teacherId !==null){
    ElMessage.error('只能选择一个导师')
    return
  }
  AddProject.value.teacherId = teacher.id; // 假设教师对象有 id 和 name 字段
  AddProject.value.teacherName = teacher.name;
  selete_teacher.value = teacher;
  teacher_display.value = false; // 关闭弹窗
  ElMessage.success(`导师 ${teacher.name} 已添加`);
};
//移除老师
const removeTeacher = (teacher) => {
  AddProject.value.teacherId = null;
  AddProject.value.teacherName = null;
  selete_teacher.value = null;
  ElMessage.success(`导师 ${teacher.name} 已移除`);
};
</script>

<template>
  <el-form :model="AddProject" label-width="80px" style="width:200%;">
    <el-form-item label="项目名称">
      <el-input v-model="AddProject.projectName" placeholder="请输入项目名称"></el-input>
    </el-form-item>
    <!--      开始和结束时间-->
    <el-form-item label="开始时间">
      <el-date-picker v-model="AddProject.startTime" type="date" placeholder="选择日期"></el-date-picker>
    </el-form-item>
    <el-form-item label="结束时间">
      <el-date-picker v-model="AddProject.endTime" type="date" placeholder="选择日期"></el-date-picker>
    </el-form-item>
    <!--      上传图片和删除图片-->
    <el-form-item label="项目图片">
      <el-upload
          action=""
          :http-request="uploadImage"
          list-type="picture-card"
          :show-file-list="false"
          accept="image/*"
      >
        <img v-if="AddProject.image" :src="AddProject.image" alt="项目图片" style="width: 100px; height: 100px;" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <el-button style="margin-left: 10px;" v-if="AddProject.image" type="danger" @click="handleDeleteImage">删除图片</el-button>
    </el-form-item>

    <!--      实验室-->
    <el-form-item label="实验室">
      <el-input v-model="AddProject.lab" placeholder="请输入实验室"></el-input>
    </el-form-item>
    <!--      富文本编辑器-->
    <el-form-item label="项目描述">
      <textarea  style="height: 300px; width: 100%;" v-model="AddProject.description" :options="editorOptions"></textarea>
    </el-form-item>
  </el-form>

  <div style="display:grid; width: 220%; margin-top: 20px;" >
    <h2>导师信息</h2>
    <el-table v-if="selete_teacher != null" :data="[selete_teacher]" border>
      <!--          头像-->
      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="140"></el-table-column>
      <el-table-column prop="major" label="研究方向" width="140"></el-table-column>
      <el-table-column prop="professional" label="职称" width="140"></el-table-column>
      <el-table-column prop="phone" label="电话" width="140"></el-table-column>
      <!--        移除按钮-->
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="danger" @click="removeTeacher">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button v-if="selete_teacher == null" style="width: 100px; margin-left: 100px; margin-top: 20px;" type="primary" @click="fetchTeachers(); teacher_display = true">选择导师</el-button>

    <el-button style="width: 100px; margin-left: 100px; margin-top: 20px;"  type="success" @click="handleAddProject(AddProject)">确认添加</el-button>

  </div>

  <!--  分页查询教师信息和条件查询 但是条件只有userName和professional,同样使用filters_student-->
  <el-dialog v-model="teacher_display" title="查询教师信息" width="70%" style="height: 550px;">
    <el-form :inline="true" :model="filters_teacher" style="margin-left: 60px;">
      <el-form-item label="姓名">
        <el-input v-model="filters_teacher.userName" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item label="专业">
        <el-input v-model="filters_teacher.professional" style="width: 140px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchTeachers">查询</el-button>
        <!--        重置-->
        <el-button type="success" @click="resetFilters_teacher">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="teacher_data" style="width: 100%">
      <el-table-column label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || 'https://via.placeholder.com/80'"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="100"></el-table-column>
      <el-table-column prop="age" label=" 年龄" width="150"></el-table-column>
      <el-table-column prop="major" label="研究方向"></el-table-column>
      <el-table-column prop="professional" label="职称"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button type="success" @click="handleSelectTeacher(row)">添加</el-button>
        </template>
      </el-table-column>

    </el-table>
    <!--      分页参数-->
    <el-pagination
        background
        layout="total, prev, pager, next"
        :current-page="filters_teacher.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="filters_teacher.pageSize"
        :total="teacher_total"
        @current-change=" handleTeacherPageChange"
        style="margin-top: 20px;margin-left:300px;"
    />

  </el-dialog>

</template>

<style scoped>

</style>